torque.managers =  {};
torque.panels = [];
torque.bars = [];
torque.cms = [];
torque.menus = [];
torque.stores =  [];
torque.dialogs = [];
torque.lib = {};

torque.urls.torrent = {
	start: 		torque.urls.root + 'j/torrents/start/',
	pause: 		torque.urls.root + 'j/torrents/pause/',
	remove: 	torque.urls.root + 'j/torrents/remove/',
	add:		torque.urls.root + 'j/torrents/add/',
	index: 		torque.urls.root + 'j/torrents/index/',
	recheck:	torque.urls.root + 'j/torrents/recheck/',
	check: 		torque.urls.root + 'j/torrents/check/',
	details: 	torque.urls.root + 'j/torrents/details/',
	files:		torque.urls.root + 'j/torrents/files/',
	peers: 		torque.urls.root + 'j/torrents/peers/',
	trackers:	torque.urls.root + 'j/torrents/trackers/',
	logs: 		torque.urls.root + 'j/torrents/logs/',
	comments: {
		add: 	torque.urls.root + 'j/torrents/comments/add/',
		remove:	torque.urls.root + 'j/torrents/comments/remove/',
		index:  torque.urls.root + 'j/torrents/comments/index/'
	}
};

torque.urls.file = {
	index: 	torque.urls.root + 'j/files/index/'
};

torque.urls.torque = {
	stats: torque.urls.root + 'j/torque/stats/'
};

torque.urls.icons = '/resources/images/icons/';
	

// Provides array's with a has function (has a key: true ? false)
Array.prototype.has = function(key) {
    if(typeof this[key] != 'undefined') { 
        return true;
    }else{
        return false;
    }
};

/* Adapted from: http://plugins.jquery.com/files/jquery.base64.js_1.txt */
torque.lib.utf8 = {
    encode: function(string) {
        string = string.replace(/\x0d\x0a/g, "\x0a");
        var output = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                output += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                output += String.fromCharCode((c >> 6) | 192);
                output += String.fromCharCode((c & 63) | 128);
            } else {
                output += String.fromCharCode((c >> 12) | 224);
                output += String.fromCharCode(((c >> 6) & 63) | 128);
                output += String.fromCharCode((c & 63) | 128);
            }
        }
        return output;
    },
    decode: function(input) {
        var string = "";
        var i = 0;
        var c = 0;
		var c1 = 0;
		var c2 = 0;
        while ( i < input.length ) {
            c = input.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = input.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = input.charCodeAt(i+1);
                c3 = input.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};

torque.lib.base64 = {
    keystring: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
    encode: function(input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = torque.lib.utf8.encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output + torque.lib.base64.keystring.charAt(enc1) + torque.lib.base64.keystring.charAt(enc2) + torque.lib.base64.keystring.charAt(enc3) + torque.lib.base64.keystring.charAt(enc4);
        }
        return output;
    },
    decode: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = torque.lib.base64.keystring.indexOf(input.charAt(i++));
            enc2 = torque.lib.base64.keystring.indexOf(input.charAt(i++));
            enc3 = torque.lib.base64.keystring.indexOf(input.charAt(i++));
            enc4 = torque.lib.base64.keystring.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = torque.lib.utf8.decode(output);
        return output;
    }
};

torque.converter = {
    link: {
        download: function(value, metaData, record) {
            if(record.get('type') == 'folder') {
                return record.get('name');
            }else{
                path = record.get('path');
                return '<a href="' + torque.urls.downloads + path +'">'+record.get('name')+'</a>';
            }
        }
    },
    numeric: {
        rounded: function(value) {
            return (Math.round(value*100)/100);
        },
        percentage: function(value) {
            return torque.converter.numeric.rounded(value*100)+'%';
        }
    },
    /* Converts a word into an HTML image (used for icons mostly) */
    img: {
        extension_action: function(extension, meta, record) {
            img = torque.converter.img.extension(extension);
            var command = '';
            if(extension.match(/rar|r[0-9]*|zip|tar|gz|bz2/i)) {
                command = 'torque.extract(\''+record.get('path')+'\')';
            }else{
                return img;
            }
            return '<a href="javascript:'+command+'">'+img+'</a>';
        },
        extension: function(extension) {
            extension_list = [];
            extension_list['mkv'] = 'fam/film.png';
            extension_list['avi'] = 'fam/film.png';
            extension_list['mp4'] = 'fam/film.png';
            extension_list['flv'] = 'fam/film.png';
            extension_list['bmp'] = 'fam/image.png';
            extension_list['jpg'] = 'fam/image.png';
            extension_list['gif'] = 'fam/image.png';
            extension_list['sfv'] = 'fam/page_white_text.png';
            extension_list['nfo'] = 'fam/page_white_text.png';
            extension_list['txt'] = 'fam/page_white_text.png';
            extension_list['folder'] = 'fam/folder.png';
            extension_list['rar'] = 'fam/compress.png';
            
            if(extension === '') {
                extension = 'fam/page.png';
            }else if(extension_list.has(extension)) {
                extension = extension_list[extension];
            }else{
                extension = 'fam/page.png';
            }

            return '<img src="' + torque.urls.icons + extension + '" />';
        },
        country: function(country) {
            return '<img src="/resources/images/icons/countries/'+country.toLowerCase()+'.png" />';
        }
    },
    progress: {
        meter: function(percent) {
            return '<div style="height:50%;text-size:8px;width:95%;border:1px #000000 solid"><div style="width:'+percent+'%;background-color:#1111aa">'+percent+'%</div></div>';
        }
    },
    /* Converts bytes into a more human readable transfer rate */
    transfer: function(bytes) {
        if(bytes > 0) {
            return torque.converter.size.best(bytes)+'s';
        }else{
            return '0Bs';
        }
    },
    /* Converts bytes into a more human readable format */
    size: {
    /* Automatically calculates the best size */
        best: function(bytes) {
            if(bytes >= 1099511627776){
                return Math.round(torque.converter.size.tb(bytes)*100)/100+'TiB';
            }
            if(bytes >= 1073741824){
                return Math.round(torque.converter.size.gb(bytes)*100)/100+'GiB';
            }
            if(bytes >= 1048576){
                return Math.round(torque.converter.size.mb(bytes)*100)/100+'MiB';
            }
            if(bytes >= 1024){
                return Math.round(torque.converter.size.kb(bytes)*100)/100+'KiB';
            }
            if(bytes > 0) {
                return Math.round(bytes*100)/100+'B';
            }
            if(bytes <= 0) {
                return '';
            }
            return Math.round(bytes*100)/100+'B';
        },
        /* Return size in kilobytes */
        kb: function(bytes){
            return (bytes / 1024);
        },
        /* Return size in megabytes */
        mb: function(bytes){
            return (bytes / 1048576);
        },
        /* Return size in gigabytes */
        gb: function(bytes){
            return (bytes / 1073741824);
        },
        /* Return size in terabytes */
        tb: function(bytes){
            return (bytes / 1099511627776);
        }
    },
    /* Returns time in a more human readable format */
    time: {
        best: function(seconds) {
            if(seconds >= 870912000) { 
                return '\u221E';
            }
            if(seconds >= 217728000) { 
                return Math.round(torque.converter.time.years(seconds)*100)/100+'y'; 
            }
            if(seconds >= 18144000) { 
                return Math.round(torque.converter.time.months(seconds)*100)/100+'mn';
            }
            if(seconds >= 604800) { 
                return Math.round(torque.converter.time.weeks(seconds)*100)/100+'w';
            }
            if(seconds >= 86400) { 
                return Math.round(torque.converter.time.days(seconds)*100)/100+'d';
            }
            if(seconds >= 3600) { 
                return Math.round(torque.converter.time.days(seconds)*100)/100+'h';
            }
            if(seconds >= 60) { 
                return Math.round(torque.converter.time.minutes(seconds)*100)/100+'m';
            }
            if(seconds < 60 && seconds > 0) { 
                return Math.round(seconds*100)/100+'s';
            }
            if(seconds <= 0) { 
                return '\u2713';
            }
            return Math.round(seconds*100)/100+'s';
        },
        years: function(seconds) {
            return (seconds/217728000);
        },
        months: function(seconds){
            return (seconds/18144000);
        },
        weeks: function(seconds) {
            return (seconds/604800);
        },
        days: function(seconds) {
            return (seconds/86400);
        },
        hours: function(seconds) {
            return (seconds/3600);
        },
        minutes: function(seconds) {
            return (seconds/60);
        }
    }
};

torque.initialize = function() {
	/* Create the viewport that holds the layout of Torque */
    torque.viewport = new Ext.Viewport({
        layout: 'border',
        items: [
            torque.panels['top'],
            torque.panels['bottom'],
            torque.panels['center']
        ],
		bbar: torque.bars['copyright'],
        stateful: true
    });
	/* Initialize the torrent store */
    torque.stores['main.torrents'].load({
		params: {
			start: 0, limit:20
		}
	});
	
    window.setInterval('torque.ajax()',5000);
};

torque.users = {};

/* User message handling */
torque.message = function(message) {
	console.log(message);
};

/* Torrent handler */
torque.torrents = {
    activeHash: null,
	details: function(obj) {
		/* FIXME */
		var record = obj.getAt(0);
		document.getElementById('details_num_peers').innerHTML = record.get('num_peers');
		document.getElementById('details_num_seeds').innerHTML = record.get('num_seeds');
		document.getElementById('details_num_pieces').innerHTML = record.get('num_pieces');
		document.getElementById('details_next_announce').innerHTML = record.get('next_announce');
		document.getElementById('details_hash').innerHTML = record.get('hash');
		document.getElementById('details_active_time').innerHTML = torque.converter.time.best(record.get('active_time'));
		document.getElementById('details_seeding_time').innerHTML = torque.converter.time.best(record.get('seeding_time'));
		document.getElementById('details_time_added').innerHTML = record.get('time_added');
		document.getElementById('details_tracker_host').innerHTML = record.get('tracker_host');
		document.getElementById('details_tracker_status').innerHTML = record.get('tracker_status');
	},
	/* Start designated torrent */
	start: function(hash) {
		if(hash !== null) {
			var conn = new Ext.data.Connection();
			conn.request({
				url: torque.urls.torrent.start,
				method: 'GET',
				params: {"hash": hash},
				success: function(responseObject) {
					var obj = Ext.decode(responseObject.responseText);
					if(obj.success !== undefined) {
						torque.message('Torrent started successfully.');
						torque.stores['main.torrents'].reload();
					}else if(obj.error !== undefined) {
						torque.message('Could not start torrent!');
					}                                 
				},
				failure: function() {
					torque.message('Could not start torrent!');
				}
			});
		}
	},
	/* Pause designated torrent */
	pause: function(hash) {
		if(hash !== null) {
			var conn = new Ext.data.Connection();
			conn.request({
				url: torque.urls.torrent.pause,
				method: 'GET',
				params: {"hash": hash},
				success: function(responseObject) {
					var obj = Ext.decode(responseObject.responseText);
					if(obj.success !== undefined) {
						torque.message('Torrent paused successfully.');
						torque.stores['main.torrents'].reload();
					}else if(obj.error !== undefined) {
						torque.message('Could not pause torrent!');
					}                                 
				},
				failure: function() {
					torque.message('Could not pause torrent!');
				}
			});
		}
	},
	/* Remove designated torrent */
	remove: function(hash,deleteData) {
		if(hash !== null) {
			var genParams;
			
			if(deleteData) {
				genParams = {"hash":hash, "data":1};
			}else{
				genParams = {"hash":hash};
			}
			
			var conn = new Ext.data.Connection();
			conn.request({
				url: torque.urls.torrent.remove,
				method: 'GET',
				params: genParams,
				success: function(responseObject) {
					var obj = Ext.decode(responseObject.responseText);
					if(obj.success !== undefined) {
						torque.message('Torrent removed successfully.');
						torque.stores['main.torrents'].reload();
					}else if(obj.error !== undefined) {
						torque.message('Could not remove torrent!');
					}                                 
				},
				failure: function() {
					torque.message('Could not remove torrent!');
				}
			});
		}
	},
	/* Generates a filter params that will be used as parameters in the query */
    generateFilterParams: function() {
		params = {};
		
        search = document.getElementById('filter_search').value;
        if(search !== '') {
            params.search = search;
			return params;
        } 
        
        age = document.getElementById('filter_age').value;
        if(age === '') {
            ageStr = '';
        }else{
            age = parseInt(age,10);
            if(age != -1 && age != "NaN") {
                /* We are getting in days, but we want to submit hours! */
                params.age = age * 24;
            }
        }
        
        /* Get the users */
        userMenu = Ext.getCmp('user-menu');
        count = userMenu.items.getCount();
        users = [];
        userCount = 0;
        for(x = 0; x < count; x++) {
            item = userMenu.items.get(x);
            if(item.checked){
                users[userCount] = item.text;
                userCount +=1;
            }
        }
        
        if(users.length > 0) {
            userStr = '';
            for(x = 0; x < users.length; x++) {
                if(x !== 0) {
                    userStr += ','+users[x];
                }else{
                    userStr += users[x];
                }
            }
			params.user = userStr;
        }
        
        /* Get the states */
        stateMenu = Ext.getCmp('state-menu');
        count = stateMenu.items.getCount();
        states = [];
        stateCount = 0;
        for(x = 0; x < count; x++) {
            item = stateMenu.items.get(x);
            if(item.checked) {
                states[stateCount] = item.text;
                stateCount += 1;
            }
        }
        
        if(states.length > 0) {
            stateStr = '';
            for(x = 0; x < states.length;x++) {
                if(x !== 0) {
                    stateStr += ','+states[x];
                }else{
                    stateStr += states[x];
                }
            }
            params.state = stateStr;
        }
        
        return params;       
    },
	/* Clears the active torrent */
	clearActive: function() {
		torque.torrents.activeHash = null;
	},
	/* Sets the active torrent by provided hash value */
    setActive: function(hash) {
        torque.torrents.activeHash = hash;
    },
	/* Sets the active torrent by selected row value */
    setActiveTorrent: function(row) {
        torque.torrents.setActive(torque.stores['main.torrents'].getAt(row).get('hash'));
    },
	/* Sets the active torrent by selected row value and sets the active file */
    setActiveShowFiles: function(obj,row) {
        torque.torrents.setActive(torque.store['main.torrents'].getAt(row).get('hash'));
        torque.files.setActive(torque.stores['main.torrents'].getAt(row).get('base64'));
    },
	/* Comment handler for torrents */
	comments: {
		activeId: null
	}
};

torque.files = {
    activePath: '',
    setActive: function(path,base64) {
        torque.panels['center'].setActiveTab(1);
        torque.files.activePath = base64;
        torque.files.updateNodes(path,base64);
	torque.stores['main.files'].removeAll();
        torque.stores['main.files'].reload({
            params: {
                'folder': base64
            }
        });
    },
	/* Sets the active file to the provided base64 path */
    setActiveFile: function(row) {
	torque.files.activePath = torque.stores['main.torrents'].getAt(row).get('base64')
    },
	/* Sets the active path by the selected button */
    setActiveByButton: function(obj) {
	path = obj.getId().replace('path','').split('^')[0];
	base64 = obj.getId().replace('path','').split('^')[1];
        torque.files.setActive(path,base64);
    },
    /* Sets the active path by the selected row */
    setActiveByRow: function(row) {
        if(torque.stores['main.files'].getAt(row).get('type') == 'folder') {
	    path = torque.stores['main.files'].getAt(row).get('path');
	    base64 = torque.stores['main.files'].getAt(row).get('base64');
            torque.files.setActive(path,base64);
        }
    },
    /* Breaks a base64 path into a series of nodes */
    getNodes: function(path) {
        paths = path.split('/');
        var nodes = [];
        if(path.charAt(-1) == '/') {
            lastIsFolder = true;
        }else{
            lastIsFolder = false;
        }
        node_count = 0;
        pathStr = '';
	console.log(paths.length);
        for(i = 0; i < paths.length; i++) {
            if(paths[i].length > 0) {
                name = paths[i];
		console.log(name)
                pathStr += paths[i] + '/';
                var node = {
                    'name': name,
                    'base64': torque.lib.base64.encode(pathStr),
		    'path': pathStr.substr(0,pathStr.length-1)
                };
                nodes[node_count] = node;
                node_count++;
            }
        }
        return nodes;
    },
    /* Updates the visual nodes for the file path in the main files tab */
    updateNodes: function(path,base64) {
        nodes = torque.files.getNodes(path,base64);
	console.dir(nodes);
        bar = torque.bars['main.files.tbar'];
        bar.removeAll();

        for(i = -1; i < nodes.length; i++) {
            if(i == -1) {
                path = '';
                name = '/';
		base64 = '';
            }else{
                path = nodes[i].path;
                name = nodes[i].name;
		base64 = nodes[i].base64;
            }
            bar.addButton({
                text: name,
                iconCls: 'icon-generic-folder',
                id: 'path'+path+'^'+base64,
                listeners: {
                    'click': {
                        fn:  function(obj) {
				torque.files.setActiveByButton(obj);
			},
                        scope: this,
                        delay: 100
                    }
                }
            });
            if(i > -1 && i+1 < nodes.length) {
                bar.addItem(new Ext.Toolbar.TextItem({text: '/'}));
            }
        }
        nodes = [];
	bar.doLayout();
    }
};

torque.ajax = function() {
    torque.stores['main.torrents'].reload();
    var conn = new Ext.data.Connection();
    conn.request({
        url: torque.urls.torque.stats,
        method: 'GET',
        success: function(responseObject) {
            var obj = Ext.decode(responseObject.responseText);
            document.getElementById('stats_hdd_total').innerHTML = torque.converter.size.best(obj.hdd_total); 
            document.getElementById('stats_hdd_available').innerHTML = torque.converter.size.best(obj.hdd_available);                           
            document.getElementById('stats_upload_speed').innerHTML = torque.converter.transfer(obj.up_speed);  
            document.getElementById('stats_download_speed').innerHTML = torque.converter.transfer(obj.down_speed);  
            document.getElementById('stats_torrents').innerHTML = obj.torrents;
            document.getElementById('stats_users').innerHTML = obj.users;           
        }
    });
};

torque.media = {
    somethingopened: false,
    savestate: function() {
        if(torque.media.somethingopened) {
            vlc = document.getElementById('vlc');
            torque.media.time = vlc.input.time;
        }
    },
    restorestate: function() {
        if(torque.media.somethingopened) {
            vlc = document.getElementById('vlc');
            vlc.playlist.clear();
            vlc.playlist.add(torque.media.url);
            vlc.playlist.play();
//            vlc.input.time = torque.media.time;
        }
    },
    open: function(url) {
        torque.media.somethingopened = true;
        torque.media.url = url;
        torque.media.time = 0;
    }
};


torque.managers.panels = {
	bottom: {
		/* Enables all the bottom torrent tabs */
		enable: function() {
			torque.panels['torrent.details'].enable();
			torque.panels['torrent.files'].enable();
			torque.panels['torrent.peers'].enable();
			torque.panels['torrent.trackers'].enable();
			//torque.panels['torrent.options'].enable();
			torque.panels['torrent.comments'].enable();
			torque.panels['torrent.logs'].enable();
		},
		disable: function() {
			torque.panels['torrent.details'].disable();
			torque.panels['torrent.files'].disable();
			torque.panels['torrent.peers'].disable();
			torque.panels['torrent.trackers'].disable();
			//torque.panels['torrent.options'].disable();
			torque.panels['torrent.comments'].disable();
			torque.panels['torrent.logs'].disable();
		}
	},
	update: {
		/* Updates the current visible torrent information tab. */
		active: function() {
			if(torque.panels['torrent.details'].isVisible()) {
				torque.stores['torrent.details'].reload();
				return;
			}
			if(torque.panels['torrent.files'].isVisible()) {
				torque.stores['torrent.files'].reload();
				return;
			}
			if(torque.panels['torrent.peers'].isVisible()) {
				torque.stores['torrent.peers'].reload();
				return;
			}
			if(torque.panels['torrent.trackers'].isVisible()) {
				torque.stores['torrent.trackers'].reload();
				return;
			}
			if(torque.panels['torrent.comments'].isVisible()) {
				torque.stores['torrent.comments'].reload();
				return;
			}
			/*if(torque.panels['torrent.options'].isVisible()) {
				torque.stores['torrent.options'].reload();
				return;
			}*/
			if(torque.panels['torrent.logs'].isVisible()) {
				torque.stores['torrent.logs'].reload();
				return;
			}	
		}
	}
};

torque.managers.navigation = {
	/* Enables the start, stop and delete navigation buttons. */
	enable: function() {
		/* Numbers are weird because toolbar has spacers */
		torque.panels['top'].items.get(2).enable(); // Start
		torque.panels['top'].items.get(4).enable(); // Stop
		torque.panels['top'].items.get(6).enable(); // Delete
	},
	/* Disables the start, stop and delete navigation buttons. */
	disable: function() {
		 /* Numbers are weird because toolbar has spacers */
		torque.panels['top'].items.get(2).disable(); // Start
		torque.panels['top'].items.get(4).disable(); // Stop
		torque.panels['top'].items.get(6).disable(); // Delete
	}
};

Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
    expires: new Date(new Date().getTime()+(1000*60*60*24*7)) //7 days from now
}));

// BARS
// Torrent comment bar
torque.bars['torrent.comments.tbar'] = new Ext.Toolbar({
    items: [
        new Ext.Button({
            text: 'Add',
            iconCls: 'icon-generic-add',
            handler: function() { 
                if(torque.torrents.activeHash === null) {
                    Ext.Msg.alert('No Selection', 'Please select a torrent first!');
                }else{
                    Ext.Msg.prompt('Comments', 'Please enter your comment:', function(btn, text){
                        if (btn == 'ok'){
                            var conn = new Ext.data.Connection();
                            conn.request({
                                url: torque.urls.torrent.comments.add,
                                method: 'GET',
                                params: {"hash": torque.torrents.activeHash, "comment": text},
                                success: function(responseObject) {
                                    var obj = Ext.decode(responseObject.responseText);
                                    if(obj.success !== undefined) {
                                        torque.stores['torrent.comments'].reload();
										torque.message('Comment added.');
                                    }else if(obj.error !== undefined) {
                                        torque.message('Could not add comment: ' + obj.error);
                                    }                                 
                                },
                                failure: function() {
                                    torque.message('Could not add comment!');
                                }
                            });
                        }
                    });
                }               
            }
        }),
        new Ext.Button({
            text: 'Delete',
            iconCls: 'icon-generic-delete',
            disabled: true,
            handler: function() { 
                var conn = new Ext.data.Connection();
                conn.request({
                    url: torque.urls.torrent.comments.remove + torque.torrents.comments.activeId,
                    method: 'GET',
                    success: function(responseObject) {
                        var obj = Ext.decode(responseObject.responseText);
                        if(obj.success !== undefined) {
                            torque.stores['torrent.comments'].reload();
							torque.message('Comment deleted.');
                        }else if(obj.error !== undefined) {
                            torque.message('Comment not deleted: ' + obj.error);
                        }
                    },
                    failure: function() {
                        torque.message('Could not delete comment.');
                    }
                });
            }
        })
    ]
});

// Torrent file bar
torque.bars['torrent.files.bbar'] = new Ext.Toolbar({
    items: [
        new Ext.Button({
            text: 'Recheck Files',
            iconCls: 'icon-generic-refresh',
            handler: function() {
                Ext.Msg.confirm('Recheck Files?', 'Are you sure you want to recheck the files(it may take a while)?', function(btn){
                        if (btn == 'yes'){
                            var conn = new Ext.data.Connection();
                            conn.request({
                                url: torque.urls.torrent.recheck + torque.torrents.activeHash,
                                method: 'GET',
                                success: function(responseObject) {
                                    var obj = Ext.decode(responseObject.responseText);
                                    if(obj.success !== undefined) {
                                        torque.stores['torrents'].reload();
                                    }else if(obj.error !== undefined) {
                                        torque.message('Could not recheck files: ' + obj.error);
                                    }                                 
                                },
                                failure: function() {
                                    torque.message('Could not recheck files!');
                                }
                            });
                        }
                    });
            }
        })
    ]
});

// Files bar
torque.bars['main.files.tbar'] = new Ext.Toolbar({
    items: [{text:'/',iconCls:'icon-generic-folder'}]
});

// Media bar
torque.bars['main.media.bbar'] = new Ext.Toolbar({
    items: [
        {
            text: 'Play',
            iconCls: 'icon-generic-play',
            handler: function() { document.getElementById('vlc').playlist.play(); }
        },
        {
            text: 'Pause',
            iconCls: 'icon-generic-pause',
            handler: function() { document.getElementById('vlc').playlist.togglePause(); }
        },
        {
            text: 'Stop',
            iconCls: 'icon-generic-stop',
            handler: function() { document.getElementById('vlc').input.time = prompt('Enter time'); }
        }   
    ]
});

// Torrents bar
torque.menus['main.torrent.userfilter'] = new Ext.menu.Menu({
    style:{ 'overflow': 'visible'},
    id: 'user-menu',
    text: 'hi',
    items: [{
        text: 'jason',
        name: 'jason',
        checked: false
    },
    {
        name: 'marc',
        text: 'marc',
        checked: false
    },
    {
        name: 'kyle',
        text: 'kyle',
        checked: false
    }]
});

torque.menus['main.torrent.statefilter'] = new Ext.menu.Menu({
    style:{ 'overflow': 'visible'},
    id: 'state-menu',
    text: 'hi',
    items: [{
        text: 'Downloading',
        checked: false
    },{
        text: 'Seeding',
        checked: false
    },{
        text: 'Checking',
        checked: false
    },{
        text: 'Paused',
        checked: false
    },{
        text: 'Error',
        checked: false
    }]
});

torque.bars['main.torrents.tbar'] = new Ext.Toolbar({
    height:25,
    items: [
		{
			text:'Users',
			menu: torque.menus['main.torrent.userfilter']
		},{
			text:'States',
			menu: torque.menus['main.torrent.statefilter']
		},{
			xtype:'tbseparator'
		},{
			xtype:'tbtext',
			text: 'Age:  '
		},{
			id:'filter_age',
			xtype:'spinnerfield',
			minValue:-1,
			incrementValue:1,
			allowDecimals:false,
			width:100
		},{
			xtype:'tbseparator'
		},{
			xtype:'tbtext',
			text:'Search:  '
		},
		new Ext.form.TextField({
			id:'filter_search',
			listeners: {
				'specialkey': {
					fn: function(obj,e) { 
						if(e.keyCode == 13) {
							torque.stores['main.torrents'].reload();
						} 
					},
					scope: this,
					delay: 100
				}
			}
		})
	],
    border:false
});

// Copyright Bar
torque.bars['copyright'] = new Ext.Toolbar({
    height:25,
    items: 'Torque "'+torque.version.name+'" [ver. '+torque.version.number+'] | Powered by: Deluge, Python, FamFamFam, Django, ExtJS, Debian, NGinx, and MySQL. Created by Jason Reid.',
    border:false
});

// Status bar
torque.bars['main.status'] = new Ext.Toolbar({
	height:25,
    text: 'Torque Interface',
    border:false,
	items: [ 
        { xtype:'tbtext',
          style: { fontWeight:'bold',color:'red'},
          text: 'Notifications: '
        },
        { xtype:'tbtext',
          style: { color:'red'},
          id: 'notification_text',
          text:'None'
        },         
        { xtype:'tbfill' },
        new Ext.Toolbar.TextItem('<img src="'+torque.urls.icons+'fam/drive.png" />'),
        { xtype: 'tbtext',
          text: '250.00GB',
          id: 'stats_hdd_available'
        },
        ' - ',
        new Ext.Toolbar.TextItem('<img src="'+torque.urls.icons+'fam/drive_web.png" />'),
        { xtype: 'tbtext',
          text: '250.00GB',
          id: 'stats_hdd_total'
        },
        ' - ',
        new Ext.Toolbar.TextItem('<img src="'+torque.urls.icons+'fam/arrow_out.png" />'),
        { xtype: 'tbtext',
          text: '250.00GB',
          id: 'stats_upload_speed'
        },
        ' - ',
        new Ext.Toolbar.TextItem('<img src="'+torque.urls.icons+'fam/arrow_in.png" />'),
        { xtype: 'tbtext',
          text: '250.00GB',
          id: 'stats_download_speed'
        },
        ' | ',
        new Ext.Toolbar.TextItem('<img src="'+torque.urls.icons+'fam/report_user.png" />'),
        { xtype: 'tbtext',
          text: '250.00GB',
          id: 'stats_users'
        },
        ' - ',
        new Ext.Toolbar.TextItem('<img src="'+torque.urls.icons+'fam/application_cascade.png" />'),
        { xtype: 'tbtext',
          text: '250.00GB',
          id: 'stats_torrents'
        }
    ]
});



// DIALOGS
// Torrent add store
torque.stores['torrent.add'] = new Ext.data.Store({
    id: 'TorqueTorrentAddStore',
    autoLoad: false,
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.torrent.check,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        {
            root: 'files'
        },
        [
            {name: 'path', type: 'string', mapping: 'path'},
            {name: 'size', type: 'string', mapping: 'size'}
        ]
    ),
    listeners: {
        'beforeload': {
            fn: function(obj) {
                if(torque.torrents.addTorrentTmpPath !== null) {
					obj.setBaseParam('path',torque.torrents.addTorrentTmpPath);
				}
            }
        }
    }
});

// Torrent add column model
torque.cms['torrent.add'] = new Ext.grid.ColumnModel([
    {header: '', dataIndex: 'extension', renderer:torque.converter.img.extension, width:30},
    {header: 'Path', dataIndex: 'path', width:600},
    {header: 'Progress', dataIndex: 'progress', renderer:torque.converter.numeric.percentage, width:200},
    {header: 'Priority', dataIndex: 'priority', width:200}
]);

// Torrent add dialog
torque.dialogs['torrent.add'] = new Ext.Window({
    title: 'Add Torrent',
    plain: true,
    height: 600,
    width: 400,
    closeable: true,
    layout: 'accordion',
    items: [
        new Ext.Panel({
            title: 'Upload',
            split: true,
            width: '100%',
            height:50,
            border:false
        }),
        new Ext.Panel({
            title: 'Settings',
            region: 'south',
            split: true,
            border: false,
            width:'100%',
            height:500
        })
    ],
    bbar: new Ext.Toolbar({
        items: [
            {
                text: 'Upload'
            },
            {
                text: 'Cancel'
            }
        ]
    })
});

// Torrent details data store
torque.stores['torrent.details'] = new Ext.data.Store({
    id: 'TorqueTorrentDetailsStore',
    autoLoad: false,
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.torrent.details,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        {
            root: 'details'
        },
        [
            {name: 'hash', type: 'string', mapping: 'hash'},
            {name: 'time_added', type: 'float', mapping: 'time_added'},
			{name: 'active_time', type: 'string', mapping: 'active_time'},
            {name: 'seed_time', type: 'int', mapping: 'seeding_time'},
            {name: 'next_announce', type: 'int', mapping: 'next_announce'},
			{name: 'num_seeds', type: 'int', mapping: 'num_seeds'},
            {name: 'num_peers', type: 'int', mapping: 'num_peers'},
			{name: 'num_pieces', type: 'int', mapping: 'num_pieces'},
            {name: 'tracker_status', type: 'string', mapping: 'tracker_status'},
			{name: 'tracker_host', type: 'string', mapping: 'tracker_host'}
        ]
    ),
    listeners: {
		'beforeload': {
			fn: function(obj,row) {
				obj.setBaseParam('hash', torque.torrents.activeHash);			
			}
		},
        'load': {
            fn: function(obj,row) {
				torque.torrents.details(obj);
			}
        }        
    }
});

// Torrent details panel
torque.panels['torrent.details'] = new Ext.Panel({
    title:'Details',
    iconCls:'icon-details',
    autoScroll:true,
    disabled:true,
	el: 'details'
});

// Torrent peer store
torque.stores['torrent.peers'] = new Ext.data.Store({
    id: 'TorqueTorrentPeersStore',
    autoLoad: false,
    remoteSort: false,
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.torrent.peers,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        {
            root: 'peers'
        },
        [
            {name: 'country', type: 'string', mapping: 'country'},
            {name: 'client', type: 'string', mapping: 'client'},
            {name: 'ip', type: 'string', mapping: 'ip'},
            {name: 'up_speed', type: 'float', mapping: 'up_speed'},
            {name: 'down_speed', type: 'float', mapping: 'down_speed'},
            {name: 'progress', type: 'float', mapping: 'progress'},
            {name: 'seed', type: 'int', mapping: 'seed'}
        ]
    ),
    listeners: {
        'beforeload': {
            fn: function(obj) {
                if(torque.torrents.activeHash !== null) {
                   obj.proxy.conn.url = torque.urls.torrent.peers + torque.torrents.activeHash;
                }                            
            }
        }
    }
});

// Torrent peer column model
torque.cms['torrent.peers'] = new Ext.grid.ColumnModel([
    {header: '', dataIndex: 'country', renderer:torque.converter.img.country,  width:30},
    {header: 'IP', dataIndex: 'ip', width:200},
    {header: 'Client', dataIndex: 'client', width:200},
    {header: 'Up', dataIndex: 'up_speed', renderer:torque.converter.transfer, width:200},
    {header: 'Down', dataIndex: 'down_speed', renderer:torque.converter.transfer, width:200},
    {header: 'Progress', dataIndex: 'progress', renderer:torque.converter.numeric.percentage, width:200}
]);

// Torrent peer panel
torque.panels['torrent.peers'] = new Ext.grid.GridPanel({
    title:'Peers',
    store: torque.stores['torrent.peers'],
    cm: torque.cms['torrent.peers'],
    iconCls:'icon-peers',
    listeners: {
        'beforeshow': {
            fn: function(obj) {
                obj.getStore().removeAll();
                obj.getStore().reload();
            }
        }
    },
    autoScroll:true,
    disabled:true
});

// TORRENT TRACKERS TAB
// Torrent trackers store
torque.stores['torrent.trackers'] = new Ext.data.Store({
    id: 'TorqueTorrentTrackerStore',
    autoLoad: false,
    remoteSort: false,
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.torrent.trackers,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        {
            root: 'trackers'
        },
        [
            {name: 'tier', type: 'string', mapping: 'tier'},
            {name: 'url', type: 'string', mapping: 'url'}
        ]
    ),
    listeners: {
        'beforeload': {
            fn: function(obj) {
                if(torque.torrents.activeHash !== null) {
                   obj.proxy.conn.url = torque.urls.torrent.trackers + torque.torrents.activeHash;
                }                            
            }
        }
    }
});

// Torrent trackers column model
torque.cms['torrent.trackers'] = new Ext.grid.ColumnModel([
    {header: 'Teir', dataIndex: 'tier', width:100},
    {header: 'URL', dataIndex: 'url', width:600}
]);

// Torrent trackers panel
torque.panels['torrent.trackers'] = new Ext.grid.GridPanel({
    title:'Trackers',
    store: torque.stores['torrent.trackers'],
    cm: torque.cms['torrent.trackers'],
    iconCls:'icon-trackers',
    listeners: {
        'beforeshow': {
            fn: function(obj) {
                obj.getStore().removeAll();
                obj.getStore().reload();
            }
        }
    },
    autoScroll:true,
    disabled:true
});

// TORRENT FILES TAB
// Torrent files store
torque.stores['torrent.files'] = new Ext.data.Store({
    id: 'TorqueTorrentFilesStore',
    autoLoad: false,
    remoteSort: false,
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.torrent.files,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        {
            root: 'files'
        },
        [
            {name: 'extension', type: 'string', mapping: 'extension'},
            {name: 'path', type: 'string', mapping: 'path'},
            {name: 'priority', type: 'int', mapping: 'priority'},
            {name: 'progress', type: 'float', mapping: 'progress'}
        ]
    ),
    listeners: {
        'beforeload': {
            fn: function(obj) {
                if(torque.torrents.activeHash !== null) {
                   obj.proxy.conn.url = torque.urls.torrent.files + torque.torrents.activeHash;
                }                            
            }
        }
    }
});

// Torrent files column model
torque.cms['torrent.files'] = new Ext.grid.ColumnModel([
    {header: '', dataIndex: 'extension', renderer:torque.converter.img.extension, width:30},
    {header: 'Path', dataIndex: 'path', width:600},
    {header: 'Progress', dataIndex: 'progress', renderer:torque.converter.numeric.percentage, width:200},
    {header: 'Priority', dataIndex: 'priority', width:200}
]);

// Torrent files panel
torque.panels['torrent.files'] = new Ext.grid.GridPanel({
    title:'Files',
    store: torque.stores['torrent.files'],
    cm: torque.cms['torrent.files'],
    iconCls:'icon-files',
    bbar: torque.bars['torrent.files.bbar'],
    listeners: {
        'beforeshow': {
            fn: function(obj) {
                obj.getStore().removeAll();
                obj.getStore().reload();
            }
        }
    },
    autoScroll:true,
    disabled:true
});

// TORRENT COMMENTS TAB
// Torrent comments data store
torque.stores['torrent.comments'] = new Ext.data.Store({
    id: 'TorqueTorrentCommentStore',
    autoLoad: false,
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.torrent.comments,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        {
            root: 'comments'
        },
        [
            {name: 'id', type: 'string', mapping: 'id'},
            {name: 'user', type: 'string', mapping: 'user'},
            {name: 'comment', type: 'string', mapping: 'comment'},
            {name: 'date', type: 'string', mapping: 'date'}
        ]
    ),
    listeners: {
        'beforeload': {
            fn: function(obj) {
                if(torque.torrents.activeHash !== null) {
                   obj.proxy.conn.url = torque.urls.torrent.comments.index + torque.torrents.activeHash;
                }                            
            }
        },
        'load': {
            fn: function(obj,row) {
                comments = torque.panels['torrent.comments'];
                if(torque.torrents.comments.activeId !== null) {
                    row = torque.stores['torrent.comments'].find('id',torque.torrents.comments.activeId);
                    if(row != -1) {
                        comments.selModel.selectRow(row,true);
                    }else{
                        comments.selModel.fireEvent('rowdeselect');
                    }
                }else{
                    comments.selModel.fireEvent('rowdeselect');
                }
            }
        }        
    }
});

// Torrent comments column model
torque.cms['torrent.comments'] = new Ext.grid.ColumnModel([
    {header: 'User', dataIndex: 'user', width:100},
    {header: 'Comment', dataIndex: 'comment', width:600},
    {header: 'Date', dataIndex: 'date', width:50}
]);

// Torrent comments panel
torque.panels['torrent.comments'] = new Ext.grid.GridPanel({
    title:'Comments',
    store: torque.stores['torrent.comments'],
    cm: torque.cms['torrent.comments'],
    iconCls:'icon-comments',
    tbar: torque.bars['torrent.comments.tbar'],
    selModel: new Ext.grid.RowSelectionModel({
        singleSelect:true,
        listeners: {
            'rowselect': {
                fn: function(obj,index,record) {
                    torque.torrents.comments.activeId = record.data.id;
                    torque.bars['torrent.comments.tbar'].items.item(1).enable();
                },
                scope: this,
                delay: 100
            },
            'rowdeselect': {
                fn: function(obj,index,record) {
                    torque.torrents.comments.activeId = null;
                    torque.bars['torrent.comments.tbar'].items.item(1).disable();
                },
                scope: this,
                delay: 100
            }
        }
    }),
    listeners: {
        'beforeshow': {
            fn: function(obj) {
                obj.getStore().removeAll();
                obj.getStore().reload();
            }
        }
    },
    autoScroll:true,
    disabled:true
});

// TORRENT LOGS TAB
// Torrent logs store
torque.stores['torrent.logs'] = new Ext.data.Store({
    id: 'TorqueTorrentLogsStore',
    autoLoad: false,
    remoteSort: false,
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.torrent.logs,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        {
            root: 'logs'
        },
        [
            {name: 'user', type: 'string', mapping: 'user'},
            {name: 'action', type: 'string', mapping: 'action'},
            {name: 'ip', type: 'string', mapping: 'ip'},
            {name: 'date', type: 'int', mapping: 'date'}
        ]
    ),
    listeners: {
        'beforeload': {
            fn: function(obj) {
                if(torque.torrents.activeHash !== null) {
                   obj.proxy.conn.url = torque.urls.torrent.logs + torque.torrents.activeHash;
                }                            
            }
        }
    }
});

// Torrent column model
torque.cms['torrent.logs'] = new Ext.grid.ColumnModel([
    {header: 'User', dataIndex: 'user', width:100},
    {header: 'Action', dataIndex: 'action', width:700},
    {header: 'IP Address', dataIndex: 'ip', width:300},
    {header: 'Date', dataIndex: 'date', width:300}
]);

// Torrent log panel
torque.panels['torrent.logs'] = new Ext.grid.GridPanel({
    title:'Logs',
    store: torque.stores['torrent.logs'],
    cm: torque.cms['torrent.logs'],
    iconCls:'icon-logs',
    listeners: {
        'beforeshow': {
            fn: function(obj) {
                obj.getStore().removeAll();
                obj.getStore().reload();
            }
        }
    },
    autoScroll:true,
    disabled:true
});

// TORRENTS PANEL
torque.stores['main.torrents'] = new Ext.data.Store({
    id: 'TorqueTorrentTorrentsStore',
    autoLoad: false,
    remoteSort: true,
    baseParams: {keys:'hash,name,user,path,progress,state,download_payload_rate,upload_payload_rate,total_done,total_uploaded,total_size,ratio,eta,time_added,hasComments'},
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.torrent.index,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        { 
            root:'torrents',
            totalProperty: 'total'
        },
        [
            {name: 'hash', type: 'string', mapping: 'hash'},
            {name: 'name', type: 'string', mapping: 'name'},
            {name: 'user', type: 'string', mapping: 'user'},
            {name: 'progress', type: 'float', mapping: 'progress'},
            {name: 'base64', type: 'string', mapping: 'base64'},
            {name: 'state', type: 'string', mapping: 'state'},
            {name: 'download_payload_rate', type: 'int', mapping: 'download_payload_rate'},
            {name: 'upload_payload_rate', type: 'int', mapping: 'upload_payload_rate'},
            {name: 'total_done', type: 'int', mapping: 'total_done'},
            {name: 'total_uploaded', type: 'int', mapping: 'total_uploaded'},
            {name: 'total_size', type: 'int', mapping: 'total_size'},
            {name: 'ratio', type: 'float', mapping: 'ratio'},
            {name: 'eta', type: 'float', mapping: 'eta'},
            {name: 'hasComments', type: 'int', mapping: 'hasComments'},
            {name: 'time_added', type: 'int', mapping: 'time_added'}
        ]
    ),
    listeners: {
		'beforeload': {
			fn: function(obj) {
				params = torque.torrents.generateFilterParams();
				/* We need to reset the old base parameters */
				obj.setBaseParam('age',null);
				obj.setBaseParam('search',null);
				obj.setBaseParam('user',null);
				obj.setBaseParam('state',null);
				var param;
				for(param in params) {
					obj.setBaseParam(param, params[param]);
				}
			}	
		},
        'load': {
            fn: function(obj,row) {
                if(torque.torrents.activeHash !== null) {
                    torrents = torque.panels['main.torrents'];
                    row = torque.stores['main.torrents'].find('hash',torque.torrents.activeHash);
                    if(row != -1) {
                        torrents.selModel.selectRow(row,true);
                    }else{
                        torrents.selModel.fireEvent('rowdeselect');
                    }
                }                            
            }
        }                
    }
});

torque.cms['main.torrents'] = new Ext.grid.ColumnModel([
    {header: 'Name', dataIndex: 'name', sortable:true, width:40},
    {header: 'User', dataIndex: 'user', sortable:true, width:10},
    {header: '%', dataIndex: 'progress', sortable:true, renderer: torque.converter.numeric.rounded, width:5},
    {header: 'State', dataIndex: 'state', sortable:true,  width:10},
    {header: 'Down', dataIndex: 'download_payload_rate', sortable:true, renderer: torque.converter.transfer, width:8},
    {header: 'Up', dataIndex: 'upload_payload_rate', sortable:true, renderer: torque.converter.transfer, width:8},
    {header: 'Size', dataIndex: 'total_size', sortable:true, renderer: torque.converter.size.best, width:8},
    {header: 'Downed', dataIndex: 'total_done', sortable:true, renderer: torque.converter.size.best, width:8},
    {header: 'Uped', dataIndex: 'total_uploaded', sortable:true, renderer: torque.converter.size.best, width:8},
    {header: 'Ratio', dataIndex: 'ratio', sortable:true,renderer: torque.converter.numeric.rounded,width:8},
    {header: 'ETA', dataIndex: 'eta', sortable:true, renderer: torque.converter.time.best,width:8}
]);

torque.panels['main.torrents'] = new Ext.grid.GridPanel({
    store: torque.stores['main.torrents'],
    cm: torque.cms['main.torrents'],
    tbar: torque.bars['main.torrents.tbar'],
    bbar: new Ext.PagingToolbar({
        pageSize: 20,
        store: torque.stores['main.torrents'],
        displayInfo: true,
        displayMsg: 'Displaying topics {0} - {1} of {2}',
        emptyMsg: "No topics to display",
        items:[
            'Refresh'
        ]
    }),
    selModel: new Ext.grid.RowSelectionModel({
        singleSelect:true,
        listeners: {
            'rowselect': {
                fn: function(obj,index,record) {
                    torque.torrents.setActiveTorrent(index);
                    // Enable the panels
                    torque.managers.panels.bottom.enable();
                    torque.managers.panels.update.active();
					torque.managers.navigation.enable();
                },
                scope: this,
                delay: 100
            },
            'rowdeselect': {
                fn: function(obj,index,record) {
					torque.torrents.clearActive();
                    torque.managers.panels.bottom.disable();
					torque.managers.navigation.disable();
                },
                scope: this,
                delay: 100
            }
        }
    }),
    title: 'Torrents',
    viewConfig: {
        forceFit: true,
         getRowClass: function(record, index) {
            var c = record.get('hasComments');
            if (c > 0) {
                return 'torrent-comments';
            }
        }

    },
    listeners: {
        'rowdblclick': {
            fn: function(obj,row) {torque.torrents.setActiveShowFiles(obj,row);},
            scope: this,
            delay: 100
        }
    },
    iconCls: 'icon-torrents',
    border: false
});


Ext.override(Ext.grid.GridView, {
    //Custom method to restore scrollTop functionality
    scrollTop : function() {
        this.scroller.dom.scrollTop = 0;
        this.scroller.dom.scrollLeft = 0;
    },
    scrollToTop : Ext.emptyFn
});


// FILE PANEL
torque.stores['main.files'] = new Ext.data.Store({
    id: 'TorqueMainFilesStore',
    autoLoad: true,
    proxy: new Ext.data.HttpProxy({
        url: torque.urls.file.index,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
        {
            root: 'files',
            totalProperty: 'total'
        },
        [
            {name: 'name', type: 'string', mapping: 'name'},
            {name: 'path', type: 'string', mapping: 'path'},
            {name: 'size', type: 'int', mapping: 'size'},
            {name: 'base64', type: 'string', mapping: 'base64'},
            {name: 'extension', type: 'string', mapping: 'extension'},
            {name: 'type', type: 'string', mapping: 'type'}
        ]
    ),
    listeners: {
        'beforeload': {
            fn: function(obj) { 
		$("#"+torque.panels['main.files'].getId()).block({ message: "Loading..."}); 
	    },
            scope: this,
            delay: 100
        },
        'load': {
	    fn: function(obj) {
                $("#"+torque.panels['main.files'].getId()).unblock();
            },
            scope: this,
            delay: 100
        }
   
    },
    
    sortInfo: {field: 'type', direction: 'DESC'}
});

torque.cms['main.files'] = new Ext.grid.ColumnModel([
    {
        header: '',
        dataIndex: 'extension',
        hidden: false,
        hideable: false,
        menuDisabled: true,
        resizable: false,
        sortable: false,
        renderer: torque.converter.img.extension_action,
        width:1
    },
    {
        header: 'Name',
        dataIndex: 'path',
        width:80,
        renderer: torque.converter.link.download,
        hidden: false
    },
    {
        header: 'Size',
        dataIndex: 'size',
        width:20,
        align: 'right',
        hidden: false,
        renderer: torque.converter.size.best
    }
]);

torque.panels['main.files'] = new Ext.grid.GridPanel({
    store: torque.stores['main.files'],
    cm: torque.cms['main.files'],
    selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
    title: 'Files',
    tbar: torque.bars['main.files.tbar'],
    viewConfig: {
        forceFit: true
    },
    listeners: {
        'rowdblclick': {
            fn: function(obj,row) { torque.files.setActiveByRow(row); },
            scope: this,
            delay: 100
        }
    },
    iconCls: 'icon-files',
    border: false
});

// MEDIA PANEL
torque.panels['main.media'] = {
    html: '<embed type="application/x-vlc-plugin" pluginspage="http://www.videolan.org" version="VideoLAN.VLCPlugin.2" width="100%" height="100%" id="vlc"></embed>',
    layoutOnTabChange: true,
    title:'Media',
    deferredRender: false,
    allowDomMove: false,
    iconCls:'icon-media',
    bbar: torque.bars['main.media.bbar'],
    autoScroll:true,
    listeners: {
        'beforehide': {
            fn: function() { torque.media.savestate(); },
            scope: this,
            delay: 0
        },
        'show': {
            fn: function() { torque.media.restorestate(); },
            scope: this,
            delay: 2000
        }
    }
};

// CLIENT PANEL
torque.panels['main.client'] = new Ext.FormPanel({
    width:'1000',
    labelWidth:100,
    frame:false,
    bodyStyle:{padding:'5px 5px 0',
        borderBottom:'1px #aaa solid'},
    title: 'Client',
    iconCls: 'icon-client',
    labalAlign: 'top',
    autoScroll:true,
    layout:'column',
    items: [
        {
        columnWidth:0.5,
        layout:'form',
        border:false,
        style:{marginTop:'16px'},
        items: [{
            text: 'test',
            html: '<div align="center" style="margin:10px"><img src="/resources/images/icons/clients/'+torque.client.slug+'.png"/><br /><span style="font-size:20px">'+torque.client.name+' '+torque.client.version+'</span></div>',
            width: '100%'
        },{
            xtype:'fieldset',
            title:'Defaults',
            hideLabel:false,
            labelWidth:150,
            items: [{
                xtype:'spinnerfield',
                fieldLabel: 'Stop Seed Ratio',
                name: 'stop_seed_ratio',
                minValue: 0.5,
                maxValue: 20,
                incrementValue: 0.1,
                allowDecimals: true,
                id:'client_opt_stop_seed_ratio',
                width:100
            },{
                xtype:'checkbox',
                fieldLabel: 'Stop Seed at Ratio',
                name: 'stop_seed_at_ratio',
                id:'client_opt_stop_seed_at_ratio',
                width:250
            },{
                xtype:'checkbox',
                fieldLabel: 'Remove Torrent at Ratio',
                name: 'remove_seed_at_ratio',
                id:'client_opt_remove_seed_at_ratio',
                width:250
            },{
                xtype:'checkbox',
                fieldLabel: 'Add Paused',
                name: 'add_paused',
                id:'client_opt_add_paused',
                width:250
            }]
        },{
            xtype:'fieldset',
            title:'Connections, Throttling and Bandwidth',
            hideLabel:false,
            labelWidth:250,
            items: [{
                xtype:'spinnerfield',
                fieldLabel: 'Max Active Downloading',
                name: 'max_active_downloading',
                id:'client_opt_max_active_downloading',
                minValue:-1,
                maxValue:500,
                allowDecimals:false,
                incrementValue:1,
                accelerate:false,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Active Limit',
                name: 'max_active_limit',
                id:'client_opt_max_active_limit',
                minValue:-1,
                maxValue:500,
                allowDecimals:false,
                incrementValue:1,
                accelerate:false,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Active Seeding',
                name: 'max_active_seeding',
                id:'client_opt_max_active_seeding',
                minValue:-1,
                maxValue:250,
                allowDecimals:false,
                incrementValue:1,
                accelerate:false,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Connections Global',
                name: 'max_connections_global',
                id:'client_opt_max_connections_global',
                minValue:-1,
                maxValue:1000,
                allowDecimals:false,
                incrementValue:1,
                accelerate:false,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Connections per Second',
                name: 'max_connections_per_second',
                id:'client_opt_max_connections_per_second',
                minValue:-1,
                maxValue:200,
                allowDecimals:false,
                incrementValue:1,
                accelerate:false,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Connections per Torrent',
                name: 'max_connections_per_torrent',
                id:'client_opt_max_connections_per_torrent',
                minValue:-1,
                maxValue:250,
                allowDecimals:false,
                incrementValue:1,
                accelerate:false,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Download Speed',
                name: 'max_download_speed',
                id:'client_opt_max_download_speed',
                minValue:-1,
                allowDecimals:true,
                incrementValue:0.1,
                accelerate:true,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Download Speed per Torrent',
                name: 'max_download_speed_per_torrent',
                id:'client_opt_max_download_speed_per_torrent',
                minValue:-1,
                allowDecimals:true,
                incrementValue:0.1,
                accelerate:true,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Half Open Connnections',
                name: 'max_half_open_connections',
                id:'client_opt_max_half_open_connections',
                minValue:-1,
                maxValue:250,
                allowDecimals:false,
                incrementValue:1,
                accelerate:true,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Upload Slots Global',
                name: 'max_upload_slots_global',
                id:'client_opt_max_upload_slots_global',
                minValue:-1,
                maxValue:250,
                allowDecimals:false,
                incrementValue:1,
                accelerate:true,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Upload Slots Per Torrent',
                name: 'max_upload_slots_per_torrent',
                id:'client_opt_max_upload_slots_per_torrent',
                minValue:-1,
                maxValue:50,
                allowDecimals:false,
                incrementValue:1,
                accelerate:true,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Upload Speed',
                name: 'max_upload_speed',
                id:'client_opt_max_upload_speed',
                minValue:-1,
                allowDecimals:true,
                incrementValue:0.1,
                accelerate:true,
                width:100
            },{
                xtype:'spinnerfield',
                fieldLabel: 'Max Upload Speed per Torrent',
                name: 'max_upload_speed_per_torrent',
                id:'client_opt_max_upload_speed_per_torrent',
                minValue:-1,
                allowDecimals:true,
                incrementValue:0.1,
                accelerate:true,
                width:100
            }]
        }]
    },{
        columnWidth:0.5,
        layout:'form',
        border:false,
        bodyStyle:'padding:10px',
        items: [{
            xtype:'fieldset',
            title:'Ports',
            hideLabel:false,
            labelWidth:150,
            items: [{
                    xtype:'spinnerfield',
                    fieldLabel: 'Daemon',
                    name: 'daemon_port',
                    id:'client_opt_daemon_port',
                    minValue:1024,
                    maxValue:65536,
                    allowDecimals:false,
                    incrementValue:1,
                    accelerate:false,
                    width:100
                },{
                    xtype:'checkbox',
                    fieldLabel: 'Random Ports',
                    name: 'random_ports',
                    id:'client_opt_random_ports',
                    width:100
                },{  
                xtype: 'fieldset',
                title:'Listen Range',
                items: [{
                    xtype:'spinnerfield',
                    fieldLabel: 'Start',
                    name: 'listen_ports_start',
                    id:'client_opt_listen_ports_start',
                    minValue:1024,
                    maxValue:65536,
                    allowDecimals:false,
                    incrementValue:1,
                    accelerate:false,
                    width:100
                },{
                    xtype:'spinnerfield',
                    fieldLabel: 'End',
                    name: 'listen_ports_end',
                    id:'client_opt_listen_ports_end',
                    minValue:1024,
                    maxValue:65536,
                    allowDecimals:false,
                    incrementValue:1,
                    accelerate:false,
                    width:100
                }]
            },{  
                xtype: 'fieldset',
                title:'Outgoing range',
                items: [{
                    xtype:'spinnerfield',
                    fieldLabel: 'Start',
                    name: 'outgoing_ports_start',
                    id:'client_opt_outgoing_ports_start',
                    minValue:1024,
                    maxValue:65536,
                    allowDecimals:false,
                    incrementValue:1,
                    accelerate:false,
                    width:100
                },{
                    xtype:'spinnerfield',
                    fieldLabel: 'End',
                    name: 'outgoing_ports_end',
                    id:'client_opt_outgoign_ports_end',
                    minValue:1024,
                    maxValue:65536,
                    allowDecimals:false,
                    incrementValue:1,
                    accelerate:false,
                    width:100
                }]
            }]
        },{
            xtype:'fieldset',
            title:'Paths',
            hideLabel:false,
            labelWidth:150,
            items: [{
                xtype:'textfield',
                fieldLabel: 'Download Location',
                name: 'download_location',
                id:'client_opt_download_location',
                width:250
            },{
                xtype:'textfield',
                fieldLabel: 'Torrent File Location',
                name: 'torrentfiles_location',
                id:'client_opt_torrentfiles_location',
                width:250
            },{
                xtype:'textfield',
                fieldLabel: 'Move Completed Path',
                name: 'move_completed_path',
                id:'client_opt_move_completed_path',
                width:250
            },{
                xtype:'checkbox',
                fieldLabel: 'Move Completed Enabled',
                name: 'move_completed',
                id:'client_opt_move_completed',
                width:250
            },{
                xtype:'textfield',
                fieldLabel: 'Autoadd Location',
                name: 'autoadd_location',
                id:'client_opt_autoadd_location',
                width:250
            },{
                xtype:'checkbox',
                fieldLabel: 'Autoadd Enabled',
                name: 'autoadd_enabled',
                id:'client_opt_autoadd_enabled',
                width:250
            }]
        },{
            xtype:'fieldset',
            title:'Encryption',
            hideLabel:false,
            labelWidth:150,
            items: [{
                xtype:'textfield',
                fieldLabel: 'Level',
                name: 'enc_level',
                id:'client_opt_enc_level',
                width:250
            },{
                xtype:'textfield',
                fieldLabel: 'Incoming',
                name: 'enc_in_policy',
                id:'client_opt_enc_in_policy',
                width:250
            },{
                xtype:'textfield',
                fieldLabel: 'Outgoing',
                name: 'enc_out_policy',
                id:'client_opt_enc_out_policy',
                width:250
            },{
                xtype:'checkbox',
                fieldLabel: 'Prefer RC4',
                name: 'enc_prefer_rc4',
                id:'client_opt_enc_prefer_rc4',
                width:250
            }]
        }]
    }],
    buttons: [{
        text: 'Restore Defaults'
    },{
        text: 'Save'
    }]

});

// REGIONS
// Center region
torque.panels['center'] = new Ext.TabPanel({
    id:'panel-center',
    region: 'center',
    activeTab: 0,
    plain: true,
    hideBorders:true,
    bbar: torque.bars['main.status'],
    items: [
        torque.panels['main.torrents'],
        torque.panels['main.files'],
        torque.panels['main.media'],
        torque.panels['main.client']
    ]
});

// Top region
torque.panels['top'] = new Ext.Toolbar({
    id:'panel-top',
    region: 'north',
    plain:true,
    frame:false,
    split:false,
    style: {paddingTop:'3px',
        paddingLeft:'5px',
        paddingBotton:'5px',
        borderWidth:'0px',
        border:'0',
        height:'70px',
        backgroundImage: 'none',
        backgroundColor: '#efefef'
    },
    items:  
	[
		{
			iconCls: 'icon-main-add',
			iconAlign: 'top',
			text: 'Upload',
			handler: function() { alert('write this'); },
			scale: 'large'
		},{ 
			xtype:'tbspacer',width:10 },{
			iconCls: 'icon-main-start',
			iconAlign: 'top',
			text: 'Start',
			handler: function() { torque.torrents.start(torque.torrents.activeHash); },
			disabled:true,
			scale: 'large'
		},{ 
			xtype:'tbspacer',width:10 },{
			iconCls: 'icon-main-stop',
			iconAlign: 'top',
			text: 'Stop',
			handler: function() { torque.torrents.pause(torque.torrents.activeHash); },
			disabled:true,
			scale: 'large'
		},{ 
			xtype:'tbspacer',
			width: 10
		},{
			iconCls: 'icon-main-delete',
			iconAlign: 'top',
			text: 'Delete',
			disabled:true,
			scale: 'large',
			handler: function() { 
				 Ext.Msg.confirm('Remove Data', 'Remove data as well?', function(btn, text){
					if (btn == 'yes'){
						deleteData = true;
					}else{
						deleteData = false;
					}
					Ext.Msg.confirm('Remove Torrent','Are you sure (this is unreversible!)?',function(btn, text) {
						if(btn == 'yes') {
							torque.torrents.remove(torque.torrents.activeHash,deleteData);
						}
					});
				});
			}
		},{
			xtype:'tbfill'
		},{
			xtype:'tbtext',
			text:'<img src="/resources/images/logo1.jpg" />'
		}
	],
    height: 70
});

// Bottom region
torque.panels['bottom'] = new Ext.TabPanel({
    id:'panel-bottom',
    region: 'south',
    title: 'Information',
    collapsible: true,
    split: true,
    hideCollapseTool: false,
    animCollapse: false,
    header: true,
    activeTab: 0,
    border: true,
    height: 250,
    minSize: 150,
    maxSize: 400,
    enableTabScroll: true,
    titleCollapse: false,
    floatable: false,
    layoutOnTabChange: true,
    defaults: {autoScroll: true},
    margins: '0 0 0 0',
    stateful: true,
    items: [
        torque.panels['torrent.details'],
        torque.panels['torrent.files'],
        torque.panels['torrent.peers'],
        torque.panels['torrent.trackers'],
        torque.panels['torrent.comments'],
        torque.panels['torrent.logs']
    ]
});
